package org.mx.service.server.websocket;

import org.eclipse.jetty.websocket.api.Session;
import org.mx.TypeUtils;
import org.mx.error.UserInterfaceSystemErrorException;
import org.mx.error.UserInterfaceSystemErrorException.SystemErrors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.Getter;
import lombok.Setter;

/**
 * WebSocket连接键定义类型
 * 
 * @author john.peng
 *
 */
@Getter
@Setter
public class WsConnectKey {
	private static final Logger logger = LoggerFactory.getLogger(WsConnectKey.class);
	private String ip;
	private int port;

	/**
	 * 构造函数
	 * 
	 * @param ip   IP地址
	 * @param port 端口号
	 */
	public WsConnectKey(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	/**
	 * 构造函数
	 * 
	 * @param connectString 连接串，格式为：ip:port。
	 */
	public WsConnectKey(String connectString) {
		super();
		int index = connectString.lastIndexOf(':');
		if (index < 0 || index >= connectString.length()) {
			if (logger.isErrorEnabled()) {
				logger.error(String.format("Invalid websocket connect: %s.", connectString));
			}
			throw new UserInterfaceSystemErrorException(SystemErrors.SYSTEM_ILLEGAL_PARAM);
		}
		this.ip = connectString.substring(0, index);
		this.port = Integer.parseInt(connectString.substring(index + 1));
	}

	/**
	 * 构造函数
	 * 
	 * @param session WebSocket会话
	 * @see Session
	 */
	public WsConnectKey(Session session) {
		super();
		this.ip = TypeUtils.byteArray2Ip(session.getRemoteAddress().getAddress().getAddress());
		this.port = session.getRemoteAddress().getPort();
	}

	@Override
	public String toString() {
		return String.format("%s:%d", ip, port);
	}
}
